<script setup lang="ts">
import { getCurrentInstance, onMounted, ref } from 'vue'
import DetailTable from '@/views/project-update/month-report/detail-table.vue'
import {
  addMonthReport,
  getLastMonthReport,
  getMonthReport,
} from '@/api/project-update/month-report'
import { Message, MessageBox } from 'element-ui'
import {
  updatePeStage,
  updateProjectInventory,
} from '@/api/project-update/project-inventory'

const vm = getCurrentInstance()

const route = vm.proxy.$route
const router = vm.proxy.$router
const currentUser = vm.proxy.$store.state.user.currentUser

const handleCancel = () => {
  router.go(-1)
}

const params = route.query
const { pkid, es: status } = params

let projectId = ''
let regionId = ''

const detailTableRef = ref(null)

const compareFields = [
  {
    label: '累计计算投资（亿元）',
    key: 'addCompleteInvestment',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '年初至本月计划完成投资（亿元）',
    key: 'monthPlanTotalInvestment',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '累计更新完成改造面积（万平方米）',
    key: 'totalUpdateChangeArea',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '2024年更新完成改造面积（万平方米）',
    key: 'addUpdateChangeArea',
    renderType: 'input',
    placeholder: '请输入',
  },
]

const lastInfo = ref({})

onMounted(() => {
  if (pkid) {
    getLastMonthReport({ pkid }).then((res) => {
      if (res.success) {
        // console.log(res.data)
        lastInfo.value = res.data || {}
      }
    })
    getMonthReport({ pkid }).then((res) => {
      if (res.success) {
        detailTableRef.value.inputData(res.data || {})
        projectId = res.data?.projectMonthPlanInfo?.projectId
        regionId = res.data?.projectMonthPlanInfo?.regionId
      }
    })
  }
})

const stageOptions = ref([
  { label: '储备阶段', value: 'reserve' },
  { label: '实施阶段', value: 'implement' },
  { label: '运营阶段', value: 'manage' },
])

const getNumber = (val) => {
  return isNaN(Number(val)) ? 0 : Number(val)
}

const checkFileds = (data: any) => {
  let flag = true
  const length = compareFields.length
  for (let i = 0; i < length; i++) {
    const item = compareFields[i]
    const lastValue = getNumber(lastInfo.value[item.key])
    const currentValue = getNumber(data.projectMonthPlanInfo[item.key])
    if (currentValue < lastValue) {
      Message.error(`本月${item.label}不能小于上月填报值${lastValue}`)
      flag = false
      break
    }
  }
  return flag
}

const handleSaveClick = async (status: 0 | 1) => {
  if (!pkid) {
    return
  }
  const params = detailTableRef.value.getSubmitData()
  params.projectMonthPlanInfo.status = status
  params.projectMonthPlanInfo.pkid = pkid
  params.projectMonthPlanInfo.projectId = projectId
  params.projectMonthPlanInfo.regionId = regionId
  const oldStage = params.projectMonthPlanInfo.peStage
  const newStage = params.projectMonthPlanInfo.projectStage
  if (status === 1) {
    if (!checkFileds(params)) {
      return
    }
  }
  if (oldStage !== newStage) {
    const oldStageText = stageOptions.value.find(
      (item) => item.value === oldStage
    )?.label
    const newStageText = stageOptions.value.find(
      (item) => item.value === newStage
    )?.label
    try {
      await MessageBox.confirm(
        `确认由“${oldStageText}”切换到“${newStageText}”？确认后不可再改回“${oldStageText}”`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      updatePeStage(
        {},
        {
          id: projectId,
          stage: newStage,
        }
      ).then((res) => {
        if (res.success) {
          Message.success(res.data)
        } else {
          Message.error(res.message)
        }
      })
    } catch (e) {
      //
    }
  }
  console.log(params)
  addMonthReport(params).then((res) => {
    if (res.success) {
      Message.success(res.data)
      router.go(-1)
    } else {
      Message.error(res.message)
    }
  })
}
</script>

<template>
  <div class="add-month-report show-detail-form">
    <div class="nav">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/project-update/month-report' }"
            ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
          >
          <el-breadcrumb-item>{{
            status ? '详情' : '填报'
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="content">
      <div class="content-main">
        <detail-table ref="detailTableRef" :status="status" />
      </div>
      <div class="buttons">
        <el-button class="cancel" @click="handleCancel">取消</el-button>
        <template v-if="!status">
          <el-button class="save" type="primary" @click="handleSaveClick(0)"
            >保存</el-button
          >
          <el-button class="publish" @click="handleSaveClick(1)"
            >提交</el-button
          >
        </template>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-month-report {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;
  background-color: rgba(244, 248, 254, 1);

  .content {
    width: calc(100% - 40px);
    height: calc(100% - 70px);
    position: absolute;
    top: 65px;
    bottom: 0;

    .divider {
      width: 100%;
      height: 1px;
      background: #e7f0ff;
      border-radius: 1px 1px 0px 0px;
      margin: 20px 0;
    }

    .content-main {
      height: calc(100% - 100px);
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
      border-radius: 2px;
      padding: 13px 16px 13px 16px;
      overflow-y: auto;
    }

    .buttons {
      padding: 10px;
      display: flex;
      justify-content: center;
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);

      .el-button {
        width: 110px;
      }

      .cancel {
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e7f0ff;
        font-weight: 400;
        font-size: 16px;
        color: #8894a8;
      }

      .save {
        //background: #10a6dd;
        border-radius: 4px;
        //color: #ffffff;
      }

      .publish {
        //background: #ffffff;
        border-radius: 4px;
        //color: #10a6dd;
        //border: 1px solid #10a6dd;
      }
    }
  }
}
</style>
